package com.swipemaster.achievements;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.app.Activity;
import android.content.Context;
import android.widget.TextView;

import com.swipemaster.R;

public class AchievementsManager
{
	private Activity mActivity;
	private Achievements mAchievements;

	public AchievementsManager(Activity activity)
	{
		mActivity = activity;
		loadOrCreateAchievements();
	}

	public void updateTextViews(Activity activity)
	{
		TextView textView;
		textView = (TextView) activity.findViewById(R.id.gamesPlayed);
		textView.setText(mAchievements.getGamesPlayed() + "");
		textView = (TextView) activity.findViewById(R.id.stars);
		textView.setText(mAchievements.getStars() + "");
		textView = (TextView) activity.findViewById(R.id.challengeRecord);
		textView.setText(mAchievements.getChallengeRecord() + "");
		textView = (TextView) activity.findViewById(R.id.survivalRecord);
		textView.setText(mAchievements.getSurvivalRecord() + "s");
		textView = (TextView) activity.findViewById(R.id.avgTimeFromPuzzleRecords);
		textView.setText(mAchievements.getAvgTimeFromPuzzleRecords() + "s");
		textView = (TextView) activity.findViewById(R.id.avgTimeFromSurvivalRecords);
		textView.setText(mAchievements.getAvgTimeFromSurvivalRecords() + "s");
	}

	public void saveAchievements()
	{
		try
		{
			FileOutputStream fos = mActivity.openFileOutput(mActivity.getString(R.string.achievements), Context.MODE_PRIVATE);
			ObjectOutputStream out = new ObjectOutputStream(fos);
			out.writeObject(mAchievements);
			out.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * First, try to load achievements from file. If no such file exists, than create new achievements.
	 */
	private void loadOrCreateAchievements()
	{
		ObjectInputStream in = null;
		try
		{
			FileInputStream fis = mActivity.openFileInput(mActivity.getString(R.string.achievements)); 
			in = new ObjectInputStream(fis);
		}
		catch (FileNotFoundException e)
		{
			mAchievements = new Achievements();
			return;
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		try
		{
			mAchievements = (Achievements) in.readObject();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		try
		{
			in.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public Achievements getAchievements()
	{
		return mAchievements;
	}
	
	public LevelsInfo getLevelsInfo()
	{
		return mAchievements.getLevelsInfo();
	}
}
